package com.diy.sigmund.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.apache.ibatis.session.ResultContext;
import org.apache.ibatis.session.ResultHandler;

/**
 * @author ylm-sigmund
 * @since 2023/4/10 21:48
 */
public abstract class CommonResultHandler<T> implements ResultHandler<T> {

    protected final HttpServletResponse response;

    protected final ExcelWriter writer;

    protected WriteSheet sheet;

    protected final List<T> rowDataList;

    public HttpServletResponse getResponse() {
        return response;
    }

    public ExcelWriter getWriter() {
        return writer;
    }

    public WriteSheet getSheet() {
        return sheet;
    }

    public List<T> getRowDataList() {
        return rowDataList;
    }

    public CommonResultHandler(HttpServletResponse response, Class<? extends T> clazz) throws IOException {
        this.response = response;
        this.writer = EasyExcel.write(response.getOutputStream(), clazz).build();
        rowDataList = new ArrayList<>(1);
        this.initSheet();
    }


    public void initSheet(){
        this.sheet = EasyExcel.writerSheet().build();
    }

    @Override
    // @SneakyThrows
    public void handleResult(ResultContext<? extends T> resultContext){
        T obj = resultContext.getResultObject();
        rowDataList.add(processing(obj));
        writer.write(rowDataList,sheet);
        rowDataList.clear();
    }

    public abstract T processing(T t);
}
